package com.syqc.monitor.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isVisible
import com.permissionx.guolindev.PermissionX
import com.syqc.comlib.base.BaseBarActivity
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResult
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.toast
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityExteWebBinding
import com.syqc.monitor.databinding.IncludeWebViewBinding
import com.syqc.utils.Keys


class ExteWebActivity : BaseBarActivity<ActivityExteWebBinding>(ActivityExteWebBinding::inflate) {


    private lateinit var mWebViewVB: IncludeWebViewBinding
    override fun initView() {
//        WxShareUtil.instance.init(applicationContext)
        mWebViewVB = IncludeWebViewBinding.bind(binding.root)
        val title = intent.getStringExtra(Keys.INTENT_TITLE) ?: ""
        ToolbarHelper.setToolbar(this, title)
        val url = intent.getStringExtra(Keys.INTENT_OTHER) ?: ""
        mWebViewVB.mWebView.webViewClient = webViewClient
        mWebViewVB.mWebView.webChromeClient = webChromeClient
        mWebViewVB.mWebView.addJavascriptInterface(JsShareWx(), "JsShareWx")
        mWebViewVB.mWebView.addJavascriptInterface(this, "JsScan")
        mWebViewVB.mWebView.loadUrl(url)
//        mWebViewVB.mWebView.loadUrl("file:///android_asset/tes.html")
//        mWebViewVB.mWebView.loadUrl("http://192.168.2.122:8081/#/pages/index/index")
        initSetting()
    }

    override fun setListener() {


    }

    private fun initSetting() {
        //声明WebSettings子类
        mWebViewVB.mWebView.settings.run {
            //设置自适应屏幕，两者合用
            useWideViewPort = true //将图片调整到适合webview的大小
            //存数据到本地开关
//            domStorageEnabled = true

            loadWithOverviewMode = true // 缩放至屏幕的大小

            //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
            javaScriptEnabled = true
            //支持内容重新布局
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            //缩放操作
            setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。

            builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放

            displayZoomControls = false //隐藏原生的缩放控件

            //其它细节操作
            allowFileAccess = true //设置可以访问文件

            javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口

            loadsImagesAutomatically = true //支持自动加载图片

            defaultTextEncodingName = "utf-8" //设置编码格式


            //设置 WebView 字体的大小，默认大小为 16
            defaultFontSize = 14
            //设置 WebView 支持的最小字体大小，默认为 8
            minimumFontSize = 10
            // 5.1以上默认禁止了https和http混用，以下方式是开启
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
            //解决图片不显示
            blockNetworkImage = false
        }

    }

    private var webViewClient: WebViewClient = object : WebViewClient() {
        //设定加载开始的操作
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            binding.mProgressBar.progress = 0
            binding.mProgressBar.isVisible = true
        }

        //设定加载结束的操作
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            binding.mProgressBar.isVisible = false
        }

        /*  override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
              // 我们这个地方返回false, 并不处理它,把它交给webView自己处理.
              //解决WebView的重定向问题
              return false
          }   */
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            // 我们这个地方返回false, 并不处理它,把它交给webView自己处理.
            //解决WebView的重定向问题
            url?.let {
                if (isWeChatMiniProgramUrl(url)) { // 判断是否为微信小程序链接
                    handleWeChatMiniProgramUrl(url) // 处理微信小程序链接
                    return true // 表示已处理该URL，WebView不再加载
                }
            }
            view?.loadUrl(url ?: "")
            return true
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            request?.url?.toString()?.let {
                if (isWeChatMiniProgramUrl(it)) { // 判断是否为微信小程序链接
                    handleWeChatMiniProgramUrl(it) // 处理微信小程序链接
                    return true // 表示已处理该URL，WebView不再加载
                }
            }
            view?.loadUrl(request?.url.toString())
            return true
        }
    }

    private fun isWeChatMiniProgramUrl(url: String): Boolean {
        // 根据实际情况定义判断逻辑，例如检查URL是否包含特定的协议或参数
        return url.startsWith("weixin://") || "wxmini" in url
    }

    private fun handleWeChatMiniProgramUrl(url: String) {
        try {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
            startActivity(intent)
        } catch (e: Exception) {
            // 如果没有安装微信
            R.string.toast_share_install_wx.toast(this)
        }
    }

    private var webChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            binding.mProgressBar.progress = newProgress
        }

        override fun getDefaultVideoPoster(): Bitmap? {
            return if (super.getDefaultVideoPoster() == null) {
                BitmapFactory.decodeResource(resources, R.mipmap.ic_default_error)
            } else super.getDefaultVideoPoster()
        }

        override fun onShowFileChooser(
            webView: WebView?,
            filePathCallback: ValueCallback<Array<Uri>>?,
            fileChooserParams: FileChooserParams?
        ): Boolean {
            fileCallback = filePathCallback
            getImgFromDicm()
            return true
        }
    }

    //打开手机相机和媒体库
    private var fileCallback: ValueCallback<Array<Uri>>? = null

    //点击返回上一页面而不是退出浏览器
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebViewVB.mWebView.canGoBack()) {
            mWebViewVB.mWebView.goBack()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun onDestroy() {
        mWebViewVB.mWebView.run {
            loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            clearHistory()
            (parent as ViewGroup).removeView(this)
            destroy()
        }
        super.onDestroy()
        destroyFileCallBack()
    }

    private fun destroyFileCallBack() {
        try {
            fileCallback?.onReceiveValue(null)
            fileCallback = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun getCameraPermission() {
        PermissionX.init(this).permissions(Manifest.permission.CAMERA)
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    launcher.launchAct<ScanQrExteActivity>(this@ExteWebActivity)
                } else {
                    getString(R.string.toast_persission_set).toast(this@ExteWebActivity)
                }
            }
    }

    private val launcher = registerResult { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.let {
                val string = it.getStringExtra("ScanResult") ?: ""
                toJsScanResult(type, true, string)
            }
        } else {
            toJsScanResult(type, false, "")
        }
    }
    private var type = 0

    @JavascriptInterface
    fun toScan(type: Int) {
        this.type = type

        runOnUiThread {
            getCameraPermission()
        }

    }

    private fun toJsScanResult(type: Int, isSuccess: Boolean, result: String) {
        val loadUrl = "javascript:scanBack('$type','$isSuccess','$result')"
        mWebViewVB.mWebView.loadUrl(loadUrl);
    }


    /**
     * 从相册获取图片
     */
    private fun getImgFromDicm() {
        val photo = Intent(Intent.ACTION_PICK)
        photo.setType("image/*")
        launcherPhoto.launch(photo)
    }

    private val launcherPhoto = registerResult {
        if (it.data != null && it.data?.data != null) {
            val uri = it.data?.data
            fileCallback?.onReceiveValue(arrayOf(uri!!))
            fileCallback = null
        } else {
            fileCallback?.onReceiveValue(null)
            fileCallback = null
        }
    }
}

class JsShareWx {
    @JavascriptInterface
    fun shareWxLocation(title: String, url: String, content: String) {
//        MLog.e("被调用=====$title    $url  $content")
//        WxShareUtil.instance.shareWeb(title, url, content)
    }
}

